<template>
  <div class="admin-users">
    <h2>用户管理</h2>
    
    <!-- 搜索和添加按钮 -->
    <el-row :gutter="20" style="margin-bottom: 20px;">
      <el-col :span="8">
        <el-input
          v-model="searchQuery"
          placeholder="搜索用户名或邮箱"
          prefix-icon="el-icon-search"
          clearable
          @input="handleSearch"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary" @click="showAddDialog = true">添加用户</el-button>
      </el-col>
    </el-row>

    <!-- 用户列表 -->
    <el-table :data="filteredUsers" style="width: 100%">
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="180"></el-table-column>
      <el-table-column prop="is_admin" label="是否管理员" width="120">
        <template #default="scope">
          <el-switch
            v-model="scope.row.is_admin"
            active-text="是"
            inactive-text="否"
            @change="updateAdminStatus(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <el-button size="small" @click="editUser(scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="deleteUser(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="showAddDialog"
      :title="dialogTitle"
      width="500px"
      @close="resetForm"
    >
      <el-form
        :model="userForm"
        :rules="userRules"
        ref="userFormRef"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" type="email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item v-if="!userForm.id" label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item v-if="userForm.id" label="新密码" prop="newPassword">
          <el-input v-model="userForm.newPassword" type="password" placeholder="不修改请留空"></el-input>
        </el-form-item>
        <el-form-item label="是否管理员" prop="is_admin">
          <el-switch v-model="userForm.is_admin" active-text="是" inactive-text="否"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showAddDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '../../api/index.js'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAppStore } from '../../store'

export default {
  name: 'AdminUsers',
  setup() {
    const router = useRouter()
    const store = useAppStore()
    const users = ref([])
    const loading = ref(true)
    const searchQuery = ref('')
    const showAddDialog = ref(false)
    const userForm = ref({
      id: null,
      username: '',
      email: '',
      password: '',
      newPassword: '',
      is_admin: false
    })
    const userFormRef = ref(null)
    const userRules = {
      username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能少于6个字符', trigger: 'blur' }
      ]
    }

    // 检查是否为管理员
    onMounted(() => {
      if (!store.isLoggedIn || !store.user?.is_admin) {
        ElMessage.error('需要管理员权限')
        router.push('/')
        return
      }
      fetchUsers()
    })

    // 获取所有用户
    const fetchUsers = async () => {
      try {
        loading.value = true
        const response = await api.get('/users')
        // 检查response本身是否为数组（后端直接返回用户数组）
        // 如果不是数组，再检查是否有data字段
        if (Array.isArray(response)) {
          users.value = response
        } else if (Array.isArray(response?.data)) {
          users.value = response.data
        } else {
          users.value = []
        }
        console.log('获取到的用户数据:', users.value)
      } catch (error) {
        console.error('获取用户失败:', error)
        ElMessage.error('获取用户失败')
        // 发生错误时确保users是数组，避免后续错误
        users.value = []
      } finally {
        loading.value = false
      }
    }

    // 根据搜索条件过滤用户
    const filteredUsers = computed(() => {
      if (!searchQuery.value.trim()) {
        return users.value
      }
      const query = searchQuery.value.toLowerCase().trim()
      return users.value.filter(user => 
        user.username.toLowerCase().includes(query) || 
        user.email.toLowerCase().includes(query)
      )
    })

    // 搜索处理
    const handleSearch = () => {
      // 搜索功能由computed属性自动处理
    }

    // 添加用户
    const addUser = async () => {
      try {
        // 创建不包含id和newPassword的对象
        const { id, newPassword, ...formData } = userForm.value
        
        const response = await api.post('/users', formData)
        
        console.log('添加用户响应:', response)
        
        // 直接重新获取所有用户数据，确保数据一致性
        await fetchUsers()
        
        ElMessage.success('添加成功')
        showAddDialog.value = false
      } catch (error) {
        console.error('添加用户失败:', error)
        ElMessage.error(error.response?.data?.error || '添加用户失败')
      }
    }

    // 编辑用户
    const updateUser = async () => {
      try {
        // 创建不包含id和newPassword的对象
        const { id, newPassword, ...formData } = userForm.value
        
        // 如果有新密码，则添加到formData中
        if (newPassword) {
          formData.password = newPassword
        }
        
        const response = await api.put(`/users/${id}`, formData)
        // 更新成功后重新获取数据
        fetchUsers()
        ElMessage.success('更新成功')
        showAddDialog.value = false
      } catch (error) {
        console.error('更新用户失败:', error)
        ElMessage.error(error.response?.data?.error || '更新用户失败')
      }
    }

    // 更新管理员状态
    const updateAdminStatus = async (user) => {
      try {
        await api.put(`/users/${user.id}`, {
          is_admin: user.is_admin
        })
        ElMessage.success('更新成功')
      } catch (error) {
        console.error('更新管理员状态失败:', error)
        ElMessage.error('更新失败，请刷新页面重试')
        // 恢复原来的状态
        user.is_admin = !user.is_admin
      }
    }

    // 打开编辑对话框
    const editUser = (user) => {
      userForm.value = {
        id: user.id,
        username: user.username,
        email: user.email,
        password: '',
        newPassword: '',
        is_admin: user.is_admin
      }
      showAddDialog.value = true
    }

    // 删除用户
    const deleteUser = (id) => {
      ElMessageBox.confirm('确定要删除这个用户吗？', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await api.delete(`/users/${id}`)
          // 删除成功后重新获取数据
          fetchUsers()
          ElMessage.success('删除成功')
        } catch (error) {
          console.error('删除用户失败:', error)
          ElMessage.error(error.response?.data?.error || '删除用户失败')
        }
      }).catch(() => {
        // 取消删除
      })
    }

    // 提交表单
    const submitForm = async () => {
      await userFormRef.value.validate((valid) => {
        if (valid) {
          if (userForm.value.id) {
            updateUser()
          } else {
            addUser()
          }
        }
      })
    }

    // 重置表单
    const resetForm = () => {
      userForm.value = {
        id: null,
        username: '',
        email: '',
        password: '',
        newPassword: '',
        is_admin: false
      }
      userFormRef.value?.resetFields()
    }

    // 对话框标题
    const dialogTitle = computed(() => {
      return userForm.value.id ? '编辑用户' : '添加用户'
    })

    return {
      users,
      loading,
      searchQuery,
      showAddDialog,
      userForm,
      userFormRef,
      userRules,
      filteredUsers,
      dialogTitle,
      handleSearch,
      editUser,
      deleteUser,
      updateAdminStatus,
      submitForm,
      resetForm
    }
  }
}
</script>

<style scoped>
.admin-users {
  padding: 20px;
}

h2 {
  margin-bottom: 20px;
  color: #333;
}
</style>